﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.Providers
{
    public class PartitionWorker:IWorker
    {
        #region fields
        private Thread _WorkerThread;
        private PartitionInstruction _Instruction;
        private PartitionOutput _Output;
        private Guid _JobTicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }
        #endregion

        #region IWorker Members

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return _Output; }
        }

        public Type ComponentType
        {
            get { return typeof(PartitionComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (PartitionInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (PartitionInstruction)Instruction;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.PartitionEntities();
        }


        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.PartitionEntities));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._JobTicketID, this.GetType(), this._Instruction);
                }
            }

        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #endregion

        #region work
        private void PartitionEntities()
        {
            try
            {
                EntityProvider provider = new EntityProvider(
                    this._Instruction.DbProvider, this._Instruction.ConnStr,
                    this._Instruction.SelectSql, this._Instruction.IdAttributeName,
                    string.Empty);
                List<int> entityIDs = provider.GetEntityIDs();
                List<int> entityIDsFromPrevPartition = new List<int>();
                entityIDsFromPrevPartition.AddRange(entityIDs);
                int currentPartitionStep = 0;
                Dictionary<int, List<int>> partitionedEntities =
                    this.PartitionEntities(
                        entityIDs, provider, 
                        this._Instruction.AttrPartitions, currentPartitionStep);

                this.SavePartitionResults(this._Instruction.PartitionResultFilePath, partitionedEntities);

                this._Output = new PartitionOutput(this._Instruction.OwnerComponentID, this._JobTicketID,
                                                   partitionedEntities.Count, entityIDs.Count,
                                                   this._Instruction.PartitionResultFilePath);

                if(this.WorkerFinishedEvent!=null)
                {
                    this.WorkerFinishedEvent(this._JobTicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._JobTicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }

        private void SavePartitionResults(string resultFilePath, Dictionary<int, List<int>> partitionedEntities)
        {
            if (File.Exists(resultFilePath))
                File.Delete(resultFilePath);

            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml("<Partitions></Partitions>");
            XmlNode root = xDoc.DocumentElement;
            foreach(int partitionID in partitionedEntities.Keys)
            {
                XmlNode partitionNode = XmlDataUtil.AddElement(ref xDoc, root, "Partition");
                XmlDataUtil.UpdateAttribute(ref xDoc, partitionNode, "PartitionID", partitionID.ToString());
                List<int> entityIDs = partitionedEntities[partitionID];
                foreach(int entityID in entityIDs)
                {
                    XmlNode entityNode = XmlDataUtil.AddElement(ref xDoc, partitionNode, "Entity");
                    XmlDataUtil.UpdateAttribute(ref xDoc, entityNode, "EntityID", entityID.ToString());
                }
            }

            xDoc.Save(resultFilePath);
        }

        private Dictionary<int,List<int>> PartitionEntities(
            List<int> srcEntityIDs,
            EntityProvider provider,
            List<AttributePartition> attrPartitions,
            int currentPartitionStep)
        {
            if (currentPartitionStep < attrPartitions.Count)
            {
                AttributePartition attrPartition = attrPartitions[currentPartitionStep];
                string attrName = attrPartition.AttributeName;
                int binSize = (int)attrPartition.BinSize;
                if (binSize <= 0)
                    throw new Exception("Attribute partition is not correct, bin size must be greater than 0");

                List<Range<int>> ranges = new List<Range<int>>();
                if (attrPartition.Method == PartitionMethod.Range)
                {
                    binSize = (int) attrPartition.BinSize;
                    Range<int> range = provider.GetRange(attrName);
                    int currentVal = range.FromValue;
                    while( currentVal <range.ToValue)
                    {
                        Range<int> partitionRange = new Range<int>();
                        partitionRange.FromValue = currentVal;
                        partitionRange.ToValue = currentVal + binSize;
                        ranges.Add(partitionRange);
                        currentVal = partitionRange.ToValue;
                    }
                }
                else if(attrPartition.Method==PartitionMethod.Percent)
                {
                    binSize = (int)attrPartition.BinSize * srcEntityIDs.Count / 100;
                }
                else
                {
                    binSize = 1;
                }

                if(this.WorkerStatusChangedEvent !=null)
                {
                    int group = 1;
                    if (binSize > 0)
                        group = (int)srcEntityIDs.Count / binSize;
                    {
                        if (attrPartition.Method == PartitionMethod.Range)
                        {
                            group = ranges.Count;
                        }
                        else if(attrPartition.Method==PartitionMethod.Distinct)
                        {
                            group = provider.GetDistinctCount(attrPartition.AttributeName);
                        }
                    }
                    string msg =
                        string.Format(
                            "Trying to partition {0} entities into {1} groups, based on attribute {2}",
                            srcEntityIDs.Count, group, attrName);
                    int pct = 50;
                    this.WorkerStatusChangedEvent(this._JobTicketID, this.GetType(), this._Instruction,
                        this.WorkflowName, this.ComponentName, msg, pct);
                }

                Dictionary<int, List<int>> partitionedEntities = new Dictionary<int, List<int>>();
                if (attrPartition.Method == PartitionMethod.Range)
                    partitionedEntities =
                        provider.GetPartitionedEntityIDs(
                            srcEntityIDs, attrName,
                            this._Instruction.MinCountPerPartition,
                            ranges);
                else if (attrPartition.Method == PartitionMethod.Percent)
                    partitionedEntities =
                        provider.GetPartitionedEntityIDs(
                            srcEntityIDs, attrName, binSize);
                else
                    partitionedEntities = provider.GetPartitionedEntityIDsByDistinctAttrValue(
                        srcEntityIDs, attrName);
                if (currentPartitionStep < attrPartitions.Count - 1)
                {
                    currentPartitionStep += 1;
                    Dictionary<int, List<int>> partitionedEntities2 = new Dictionary<int, List<int>>();
                    foreach (int partitionID in partitionedEntities.Keys)
                    {
                        List<int> entityIDs = partitionedEntities[partitionID];
                        Dictionary<int, List<int>> partitionedEntities3 =
                            this.PartitionEntities(entityIDs, provider, attrPartitions, currentPartitionStep);
                        if (partitionedEntities3 == null || partitionedEntities3.Count == 0)
                        {
                            if(entityIDs !=null && entityIDs.Count>0)
                            {
                                int partitionID3 = partitionedEntities2.Count + 1;
                                partitionedEntities2.Add(partitionID3, entityIDs);
                            }
                        }
                        else
                        {
                            foreach (int partitionID2 in partitionedEntities3.Keys)
                            {
                                int partitionID3 = partitionedEntities2.Count + 1;
                                partitionedEntities2.Add(partitionID3, partitionedEntities3[partitionID2]);
                            }
                        }
                    }
                    return partitionedEntities2;
                }
                else
                    return partitionedEntities;
            }
            else
                return null;
        }
        #endregion
    }
}
